﻿using System;

namespace Util
{
    public static class Converter
    {
        public static T EnumTypeConverter<T>(string type)
        {
            T varType = (T)Enum.Parse(typeof(T), type);
            return varType;
        }

        /// <summary>
        /// 生成cron表达式
        /// </summary>
        /// <param name="intervalDays">间隔日期（1-31）</param>
        /// <param name="scheduledTime">间隔时间</param>
        /// <returns></returns>
        public static string GetCornString(int intervalDays, TimeSpan scheduledTime)
        {
            intervalDays = intervalDays > 31 ? 31 : intervalDays;
            intervalDays = intervalDays < 1 ? 1 : intervalDays;
            string cornStr = string.Format("{0} {1} {2} 1/{3} * ? *", scheduledTime.Seconds, scheduledTime.Minutes, scheduledTime.Hours, intervalDays);
            return cornStr;
        }

        public static int GetIntPortByString(string stringPort)
        {
            switch (stringPort)
            {
                case "COM1":
                    return 1;
                case "COM2":
                    return 2;
                case "COM3":
                    return 3;
                case "COM4":
                    return 4;
                case "COM5":
                    return 5;
                default:
                    break;
            }
            return 0;
        }

        /// <summary>
        /// 取小数位，非四舍五入
        /// </summary>
        /// <param name="num">取小数位的数字</param>
        /// <param name="decimalPlaces">小数位数</param>
        /// <returns></returns>
        public static double Round(double num, int decimalPlaces)
        {
            string res;
            int index = num.ToString().IndexOf(".");//取小数点所在位置索引
            if (index + 1 + decimalPlaces > num.ToString().Length || num.ToString().IndexOf(".") == -1)//索引大于长度或为整数
            {
                res = num.ToString();
            }
            else
            {
                res = num.ToString().Substring(0, index + 1 + decimalPlaces);
            }
            return Convert.ToDouble(res);
        }

    }



}
